package com.ugoodtech.mdcc.client.wechat;


import com.ugoodtech.mdcc.client.wechat.callback.AesException;
import com.ugoodtech.mdcc.client.wechat.callback.WXBizMsgCrypt;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * Created by Xiangcheng Li on 2023/11/9.
 *
 * @author Xiangcheng Li
 */

@Service
@Slf4j
public class WeChatApi {

    // public static void main(String[] args) throws AesException {
    //     WXBizMsgCrypt wxcpt = new WXBizMsgCrypt("01d5c6faf395e322d783cd31d4e84480", "ChoOlgwhIkmuTMH1fyvsjr13jLj3Q1mxSe8T0WBvXX0", "wx7480b37395fa06d2");
    //     String sMsg = wxcpt.decryptMsg("d44afa9a8e527b35007df4c6980891c7a0800a38", "1722501684", "1126920334", "<xml>\n"
    //         + "    <ToUserName><![CDATA[gh_41f207de7404]]></ToUserName>\n"
    //         + "    <Encrypt><![CDATA[thbRWYijO9GSQGz9gpZqudexdEyuJpBDPkwCMwBNA1M5ZWc8dog9JTVv6HUDpo+HqJ5dw7a3cufAGNW7TmjTVt5UXavQhGUIBP0UPWp+9fFx5j17IGfDDtCGqsKFwcvoWH+nY191PgHki9TCbrGEUw76+WymTdvlZ/B/baG/p5zpenp2EwV0DuhYzoOL+NjRgrqfjPd4FNjpSb2gKJvwZ0iS5HRlTYeduOAythRePQcGFtrFZ2nICWKjYopH0NFvNQg91tggBXxLKl9a/2vMfntmEwK8XZ3T1yPQ0KwPjbMtiGfUC5lPJ+SFJw7YMQwseNtsBtr3fNi2iCHEDwiOrlBEnGbCWyBndPe87MQ7xeAuXH9gUhaIfx7sRvitaTIuX/b5grQxEmvEm4HzQLkJcmRo5X1Org+f4nNvPJ6Bx6IUvlUe9kqdDwDOSdg27niOBkmgIXeuBiVqWlx7mEtTkg==]]></Encrypt>\n"
    //         + "</xml>");
    //     System.out.println(sMsg);
    // }


    public String verifyUrl(String sCorpID, String sToken, String sEncodingAESKey, String sVerifyMsgSig,
        String sVerifyTimeStamp, String sVerifyNonce, String sVerifyEchoStr){

        try {
        WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID);
		/*
		------------使用示例一：验证回调URL---------------
		*企业开启回调模式时，企业微信会向验证url发送一个get请求
		假设点击验证时，企业收到类似请求：
		* GET /cgi-bin/wxpush?msg_signature=5c45ff5e21c57e6ad56bac8758b79b1d9ac89fd3&timestamp=1409659589&nonce=263014780&echostr=P9nAzCzyDtyTWESHep1vC5X9xho%2FqYX3Zpb4yKa9SKld1DsH3Iyt3tP3zNdtp%2B4RPcs8TgAE7OaBO%2BFZXvnaqQ%3D%3D
		* HTTP/1.1 Host: qy.weixin.qq.com

		接收到该请求时，企业应		1.解析出Get请求的参数，包括消息体签名(msg_signature)，时间戳(timestamp)，随机数字串(nonce)以及企业微信推送过来的随机加密字符串(echostr),
		这一步注意作URL解码。
		2.验证消息体签名的正确性
		3. 解密出echostr原文，将原文当作Get请求的response，返回给企业微信
		第2，3步可以用企业微信提供的库函数VerifyURL来实现。

		*/
        // // 解析出url上的参数值如下：
        // // String sVerifyMsgSig = HttpUtils.ParseUrl("msg_signature");
        // String sVerifyMsgSig = "5c45ff5e21c57e6ad56bac8758b79b1d9ac89fd3";
        // // String sVerifyTimeStamp = HttpUtils.ParseUrl("timestamp");
        // String sVerifyTimeStamp = "1409659589";
        // // String sVerifyNonce = HttpUtils.ParseUrl("nonce");
        // String sVerifyNonce = "263014780";
        // // String sVerifyEchoStr = HttpUtils.ParseUrl("echostr");
        // String sVerifyEchoStr = "P9nAzCzyDtyTWESHep1vC5X9xho/qYX3Zpb4yKa9SKld1DsH3Iyt3tP3zNdtp+4RPcs8TgAE7OaBO+FZXvnaqQ==";
        String sEchoStr; //需要返回的明文

            sEchoStr = wxcpt.verifyUrl(sVerifyMsgSig, sVerifyTimeStamp,
                sVerifyNonce, sVerifyEchoStr);
            return sEchoStr;
            // 验证URL成功，将sEchoStr返回
            // HttpUtils.SetResponse(sEchoStr);
        } catch (Exception e) {
            //验证URL失败，错误原因请查看异常
            e.printStackTrace();
        }
        return null;
    }

    public String handleCallBack(String sCorpID, String sToken, String sEncodingAESKey,
        String sVerifyMsgSig,
        String sVerifyTimeStamp, String sVerifyNonce, String sReqData){

        /*
		------------使用示例二：对用户回复的消息解密---------------
		用户回复消息或者点击事件响应时，企业会收到回调消息，此消息是经过企业微信加密之后的密文以post形式发送给企业，密文格式请参考官方文档
		假设企业收到企业微信的回调消息如下：
		POST /cgi-bin/wxpush? msg_signature=477715d11cdb4164915debcba66cb864d751f3e6&timestamp=1409659813&nonce=1372623149 HTTP/1.1
		Host: qy.weixin.qq.com
		Content-Length: 613
		<xml>		<ToUserName><![CDATA[wx5823bf96d3bd56c7]]></ToUserName><Encrypt><![CDATA[RypEvHKD8QQKFhvQ6QleEB4J58tiPdvo+rtK1I9qca6aM/wvqnLSV5zEPeusUiX5L5X/0lWfrf0QADHHhGd3QczcdCUpj911L3vg3W/sYYvuJTs3TUUkSUXxaccAS0qhxchrRYt66wiSpGLYL42aM6A8dTT+6k4aSknmPj48kzJs8qLjvd4Xgpue06DOdnLxAUHzM6+kDZ+HMZfJYuR+LtwGc2hgf5gsijff0ekUNXZiqATP7PF5mZxZ3Izoun1s4zG4LUMnvw2r+KqCKIw+3IQH03v+BCA9nMELNqbSf6tiWSrXJB3LAVGUcallcrw8V2t9EL4EhzJWrQUax5wLVMNS0+rUPA3k22Ncx4XXZS9o0MBH27Bo6BpNelZpS+/uh9KsNlY6bHCmJU9p8g7m3fVKn28H3KDYA5Pl/T8Z1ptDAVe0lXdQ2YoyyH2uyPIGHBZZIs2pDBS8R07+qN+E7Q==]]></Encrypt>
		<AgentID><![CDATA[218]]></AgentID>
		</xml>

		企业收到post请求之后应该		1.解析出url上的参数，包括消息体签名(msg_signature)，时间戳(timestamp)以及随机数字串(nonce)
		2.验证消息体签名的正确性。
		3.将post请求的数据进行xml解析，并将<Encrypt>标签的内容进行解密，解密出来的明文即是用户回复消息的明文，明文格式请参考官方文档
		第2，3步可以用企业微信提供的库函数DecryptMsg来实现。
		*/
        // // String sReqMsgSig = HttpUtils.ParseUrl("msg_signature");
        // String sReqMsgSig = "477715d11cdb4164915debcba66cb864d751f3e6";
        // // String sReqTimeStamp = HttpUtils.ParseUrl("timestamp");
        // String sReqTimeStamp = "1409659813";
        // // String sReqNonce = HttpUtils.ParseUrl("nonce");
        // String sReqNonce = "1372623149";
        // // post请求的密文数据
        // // sReqData = HttpUtils.PostData();
        // String sReqData = "<xml><ToUserName><![CDATA[wx5823bf96d3bd56c7]]></ToUserName><Encrypt><![CDATA[RypEvHKD8QQKFhvQ6QleEB4J58tiPdvo+rtK1I9qca6aM/wvqnLSV5zEPeusUiX5L5X/0lWfrf0QADHHhGd3QczcdCUpj911L3vg3W/sYYvuJTs3TUUkSUXxaccAS0qhxchrRYt66wiSpGLYL42aM6A8dTT+6k4aSknmPj48kzJs8qLjvd4Xgpue06DOdnLxAUHzM6+kDZ+HMZfJYuR+LtwGc2hgf5gsijff0ekUNXZiqATP7PF5mZxZ3Izoun1s4zG4LUMnvw2r+KqCKIw+3IQH03v+BCA9nMELNqbSf6tiWSrXJB3LAVGUcallcrw8V2t9EL4EhzJWrQUax5wLVMNS0+rUPA3k22Ncx4XXZS9o0MBH27Bo6BpNelZpS+/uh9KsNlY6bHCmJU9p8g7m3fVKn28H3KDYA5Pl/T8Z1ptDAVe0lXdQ2YoyyH2uyPIGHBZZIs2pDBS8R07+qN+E7Q==]]></Encrypt><AgentID><![CDATA[218]]></AgentID></xml>";

        try {
            WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID);

            String sMsg = wxcpt.decryptMsg(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sReqData);
            System.out.println("after decrypt msg: " + sMsg);
            return sMsg;
            // NodeList nodelist2 = root.getElementsByTagName("AgentID");
            // String AgentID = nodelist2.item(0).getTextContent();
            // System.out.println("AgentID：" + AgentID);
            // ...
            // ...
        } catch (Exception e) {
            // TODO
            // 解密失败，失败原因请查看异常
            e.printStackTrace();
        }
        return null;
    }

    // public static void main(String[] args) throws AesException {
    //     // encrypt: <xml>    <ToUserName><![CDATA[gh_41f207de7404]]></ToUserName>    <Encrypt><![CDATA[EfKQ3U2iiQcTTmiW6s2++UCJLfu75dUjBrX3e2sfcfBg6VtAiDUm575Gcfc2NF9SWFyBK7noAIP6pH6lmgMSXTmAjMyAo8vOxd40QsEtl9bgFTkDwNxz2zqbZZHPWA43HkHwIaGKbqMRECnvndxF8bUx2dw2LAUsdTEE/Cbx+2kWV/1IeqYVUKGxOCr4TNeRKfuPiFpP+q8t+hyTGofoRAXS8cve4hkZYamkzNjfky0twp9YC4fS8VcVIZ34MbPGOwQOFZLlutr5jUD2I8698BUhy0GlZwcYStWO+E9uYhGASwaYyCMgEybVpOoDUiaAblSYhiLa7fW+F94HtXed3oexZGZ5ydavBvZejx1AmIKixw/Tl6LRxsmjeJIlKEcfojnIQtEjmpvKR9RYLxr3HxSdKiQbqnLtoD36JZgvSLU=]]></Encrypt></xml>, timestamp: 1723167721, nonce: 445302918, msgSign: d4ae5c68efc41bbdfb3fb4f27c9ae865c6aded62
    //     String sToken = "01d5c6faf395e322d783cd31d4e84480";
    //     String aeskey = "ChoOlgwhIkmuTMH1fyvsjr13jLj3Q1mxSe8T0WBvXX0";
    //     WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, aeskey, "wx7480b37395fa06d2");
    //
    //     String sReqData = "<xml>    <ToUserName><![CDATA[gh_41f207de7404]]></ToUserName>    <Encrypt><![CDATA[EfKQ3U2iiQcTTmiW6s2++UCJLfu75dUjBrX3e2sfcfBg6VtAiDUm575Gcfc2NF9SWFyBK7noAIP6pH6lmgMSXTmAjMyAo8vOxd40QsEtl9bgFTkDwNxz2zqbZZHPWA43HkHwIaGKbqMRECnvndxF8bUx2dw2LAUsdTEE/Cbx+2kWV/1IeqYVUKGxOCr4TNeRKfuPiFpP+q8t+hyTGofoRAXS8cve4hkZYamkzNjfky0twp9YC4fS8VcVIZ34MbPGOwQOFZLlutr5jUD2I8698BUhy0GlZwcYStWO+E9uYhGASwaYyCMgEybVpOoDUiaAblSYhiLa7fW+F94HtXed3oexZGZ5ydavBvZejx1AmIKixw/Tl6LRxsmjeJIlKEcfojnIQtEjmpvKR9RYLxr3HxSdKiQbqnLtoD36JZgvSLU=]]></Encrypt></xml>";
    //     String sMsg = wxcpt.decryptMsg("d4ae5c68efc41bbdfb3fb4f27c9ae865c6aded62", "1723167721", "445302918", sReqData);
    //
    // }



}
